#!/bin/sh

run_query() {
  local NAME="${CLUSTER_NAME}"
  local NAMESPACE="${CLUSTER_NAMESPACE}"
  local QUERY='SELECT 1'
  local PORT=5432
  local HOST=127.0.0.1
  local DATABASE=postgres
  local INSTANCE=0
  local CONTAINER=""
  local TYPE="postgres"
  local SSLMODE=prefer
  local USERNAME=
  local PASSWORD

  local OPT
  local OPTARG
  local OPTIND

  while getopts ":c:n:i:q:p:h:d:x:k:m:u:t:" OPT; do
    case "$OPT" in
      c) NAME="$OPTARG"
      ;;
      n) NAMESPACE="$OPTARG"
      ;;
      i) INSTANCE="$OPTARG"
      ;;
      q) QUERY="$OPTARG"
      ;;
      p) PORT="$OPTARG"
      ;;
      h) HOST="$OPTARG"
      ;;
      d) DATABASE="$OPTARG"
      ;;
      x) POD="$OPTARG"
      ;;
      k) CONTAINER="$OPTARG"
      ;;
      m) SSLMODE="$OPTARG"
      ;;
      u) USERNAME="$OPTARG"
      ;;
      t) TYPE="$OPTARG"
      ;;
      \?) echo "Invalid option -$OPTARG" >&2
      return 1
      ;;
    esac
  done

  if [ "$TYPE" = postgres ]
  then
    if [ -z "$CONTAINER" ]
    then
      CONTAINER=patroni
    fi
    if [ -z "$USERNAME" ]
    then
      USERNAME="$(kubectl -n "$NAMESPACE" get secrets "$NAME" \
        --template '{{ if index .data "superuser-username" }}{{ index .data "superuser-username" | base64decode }}{{ else }}postgres{{ end }}:{{ index .data "superuser-password" | base64decode }}')"
    fi
    PASSWORD="${USERNAME#*:}"
    USERNAME="${USERNAME%:*}"
    kubectl exec -n "$NAMESPACE" "${POD:-$NAME-$INSTANCE}" -c "$CONTAINER" -- env \
      PGPASSWORD="$PASSWORD" \
      PGCONNECT_TIMEOUT="$((5 + E2E_TIMEOUT / 10))" \
      PGSSLMODE="$SSLMODE" \
      psql -q -t -A -U "$USERNAME" -d "$DATABASE" -p "$PORT" -h "$HOST" -c "$QUERY"
  elif [ "$TYPE" = babelfish ]
  then
    if [ -z "$CONTAINER" ]
    then
      CONTAINER=postgres-util
    fi
    if [ -z "$USERNAME" ]
    then
      USERNAME="babelfish:$(kubectl -n "$NAMESPACE" get secrets "$NAME" \
        -o jsonpath='{.data.babelfish-password}' | base64 -d)"
    fi
    PASSWORD="${USERNAME#*:}"
    USERNAME="${USERNAME%:*}"
    kubectl exec -n "$NAMESPACE" "${POD:-$NAME-$INSTANCE}" -c "$CONTAINER" -- env \
      usql -q -t -A "ms://$USERNAME:$PASSWORD@$HOST:$PORT" -c "$QUERY"
  else
    echo "Unknown type $TYPE"
    return 1
  fi
}

exec_postgresutil() {
  local NAME="${CLUSTER_NAME:-stackgres}"
  local INSTANCE=0
  local NAMESPACE="${CLUSTER_NAMESPACE:-stackgres}"

  local OPT
  local OPTARG
  local OPTIND

  while getopts ":c:n:i:q:p:h:d:" OPT; do
    case "$OPT" in
      c) NAME="$OPTARG"
      shift 2
      ;;
      n) NAMESPACE="$OPTARG"
      shift 2
      ;;
      i) INSTANCE="$OPTARG"
      shift 2
      ;;
      \?) echo "Invalid option -$OPTARG" >&2
      return 1
      ;;
    esac
  done

  kubectl exec -n "$NAMESPACE" "$NAME-$INSTANCE" -c postgres-util -- sh -c "$@"
}
